package com.itheima.util;

import com.github.pagehelper.PageHelper;

import java.lang.reflect.Method;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * @Author: auuuu4
 * @Date: 2024/07/10/9:49
 * @Description: 用于分页查找，使用 {@link #selectList(Integer, Integer, Object, String, Class)}
 * 通过反射调用 mapper 的 methodName 方法，返回指定页数数据
 */
public class PageHelperUtil {
    private static final Integer DEFAULT_PAGE_NUM = 1;
    private static final Integer DEFAULT_PAGE_SIZE = 20;

    /***
     *
     * @param pageNum 查询页数
     * @param pageSize 每页大小
     * @param mapper 执行方法的对象
     * @param methodName 方法名
     * @return List
     */
    public static List selectList(Integer pageNum, Integer pageSize, Object mapper, String methodName){
        if(mapper == null || methodName == null)
            throw new NullPointerException("service 和 methodName 不能为 null");


        Method[] methods = mapper.getClass().getDeclaredMethods();
        Object list = null;

        Method method = findMethodByName(methods,methodName);

        if(method == null)
            throw new NullPointerException("方法"+methodName+"不存在");

        try {
            PageHelper.startPage(((pageNum == null || pageNum <= 0) ? DEFAULT_PAGE_NUM : pageNum), ((pageSize == null || pageSize <= 0) ? DEFAULT_PAGE_SIZE : pageSize));
            list = method.invoke(mapper);
        }catch (Exception e){
            e.printStackTrace();
        }

         return (List) list;
    }

    public static List selectList(Integer pageNum, Integer pageSize, Object mapper, String methodName,Object[] args){
        if(mapper == null || methodName == null)
            throw new NullPointerException("service 和 methodName 不能为 null");


        Method[] methods = mapper.getClass().getDeclaredMethods();
        Object list = null;

        Method method = findMethodByName(methods,methodName);

        if(method == null)
            throw new NullPointerException("方法"+methodName+"不存在");

        try {
            PageHelper.startPage(((pageNum == null || pageNum <= 0) ? DEFAULT_PAGE_NUM : pageNum), ((pageSize == null || pageSize <= 0) ? DEFAULT_PAGE_SIZE : pageSize));
            System.out.println(method.getName());
            System.out.println(method.getParameters());
            list = method.invoke(mapper,args);

        }catch (Exception e){
            e.printStackTrace();
        }

        return (List) list;
    }
    private static Method findMethodByName(Method []methods, String name){
        for(Method mt:methods){
            if(mt.getName().equals(name)){
                return mt;
            }
        }
        return null;
    }
}
